package com.neusoft.yiyang.bed.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.neusoft.yiyang.bed.client.CustomerClient;
import com.neusoft.yiyang.bed.mapper.BedMapper;
import com.neusoft.yiyang.common.entity.bed.Bed;
import com.neusoft.yiyang.common.entity.bed.BedUsage;
import com.neusoft.yiyang.bed.mapper.BedUsageMapper;
import com.neusoft.yiyang.bed.service.BedUsageService;
import com.neusoft.yiyang.common.entity.bed.vto.BedCustomerUsage;
import com.neusoft.yiyang.common.entity.customer.Customer;
import com.neusoft.yiyang.common.enums.BedStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.Date;
import java.util.Map;

@Service
public class BedUsageServiceImpl implements BedUsageService {
    @Autowired
    private BedUsageMapper bedUsageMapper;

    @Autowired
    private CustomerClient customerClient;

    @Autowired
    private BedMapper bedMapper;

    @Override
    public void addBedUsage(BedUsage bedUsage) {
        // 由前端传递结束日期，直接将结束日期设置为前端提供的值
        bedUsageMapper.insert(bedUsage);
    }

    @Override
    public void closeBedUsage(Integer bedUsageId, Date endDate) {
        BedUsage bedUsage = bedUsageMapper.selectById(bedUsageId);
        if (bedUsage != null) {
            // 更新床位使用的结束日期
            bedUsage.setEndDate(endDate);
            bedUsageMapper.updateById(bedUsage);
        }
    }

    @Override
    public List<BedUsage> getBedUsageByCustomerId(Integer customerId) {
        QueryWrapper<BedUsage> query = new QueryWrapper<>();
        query.eq("customer_id", customerId);
        return bedUsageMapper.selectList(query);
    }

    @Override
    public List<BedUsage> getBedUsageHistory(Integer bedId) {
        QueryWrapper<BedUsage> query = new QueryWrapper<>();
        query.eq("bed_id", bedId);
        return bedUsageMapper.selectList(query);
    }

    @Override
    public List<Customer> searchCustomerByName(String customerName) {
        // 使用 CustomerClient 获取 customer_id
        List<Customer> customers = customerClient.searchCustomers(customerName, null, null, null);
        if (customers.isEmpty()) {
            return null;  // 如果没有找到该客户
        }

        return customers;  // 返回客户列表，供前端展示客户信息
    }

    @Override
    public void updateBedEndTime(Integer bedUsageId, Date endDate) {
        UpdateWrapper<BedUsage> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("bed_usage_id", bedUsageId)  // 更新条件：name = '李四'
                .set("end_date", endDate);     // 更新的字段
        bedUsageMapper.update(null, updateWrapper);
    }

    @Override
    public void swapBed(Integer bedUsageId, String newRoomNumber, Integer newBedNumber) {
        QueryWrapper<BedUsage> query1 = new QueryWrapper<>();
        query1.eq("bed_usage_id", bedUsageId);
        List<BedUsage> bedUsages = bedUsageMapper.selectList(query1);
        UpdateWrapper<BedUsage> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("bed_usage_id", bedUsageId)
                .set("end_date", new Date());
        bedUsageMapper.update(null, updateWrapper);

        QueryWrapper<Bed> query2 = new QueryWrapper<>();
        query2.eq("room_number", newRoomNumber);
        query2.eq("bed_no", newBedNumber);
        List<Bed> beds = bedMapper.selectList(query2);

        QueryWrapper<Bed> query3 = new QueryWrapper<>();
        query3.eq("bed_id", bedUsages.get(0).getBedId());
        List<Bed> bed_before = bedMapper.selectList(query3);

        UpdateWrapper<Bed> updateWrapper1 = new UpdateWrapper<>();
        updateWrapper1.eq("bed_id", bedUsages.get(0).getBedId())
                .set("status", BedStatus.free);
        bedMapper.update(null, updateWrapper1);

        UpdateWrapper<Bed> updateWrapper2 = new UpdateWrapper<>();
        updateWrapper2.eq("bed_id", beds.get(0).getBedId())
                .set("status", bed_before.get(0).getStatus());
        bedMapper.update(null, updateWrapper2);

        customerClient.changeBed(bedUsages.get(0).getCustomerId(), beds.get(0).getBedId());

        BedUsage newBedUsage = new BedUsage();
        newBedUsage.setBedId(beds.get(0).getBedId());
        newBedUsage.setCustomerId(bedUsages.get(0).getCustomerId());
        newBedUsage.setStartDate(new Date());
        newBedUsage.setEndDate(bedUsages.get(0).getEndDate());
        bedUsageMapper.insert(newBedUsage);
    }

    @Override
    public BedUsage getBedusageByCid(Integer customerId) {
        QueryWrapper<BedUsage> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("customer_id", customerId)  // 客户ID
                .orderByDesc("start_date")    // 按start_date降序排列
                .last("LIMIT 1");             // 只取第一条（最新）

        return bedUsageMapper.selectOne(queryWrapper);
    }

    //更新床位记录
    @Override
    public void updateBedUsage(@RequestBody BedUsage bedUsage) {
        bedUsageMapper.updateById(bedUsage);
    }

    @Override
    public void exchangeBeds(Map<String, BedCustomerUsage> bedCustomerUsageMap) {
        BedCustomerUsage bedCustomerUsage1 = bedCustomerUsageMap.get("sourceBed");
        BedCustomerUsage bedCustomerUsage2 = bedCustomerUsageMap.get("targetBed");

        if (bedCustomerUsage1 != null && bedCustomerUsage2 != null) {
            // 获取当前时间
            Date now = new Date();

            // 更新第一个床位使用记录的结束时间
            UpdateWrapper<BedUsage> updateWrapper1 = new UpdateWrapper<>();
            updateWrapper1.eq("bed_usage_id", bedCustomerUsage1.getBedUsageId())
                    .set("end_date", now);
            bedUsageMapper.update(null, updateWrapper1);

            // 更新第二个床位使用记录的结束时间
            UpdateWrapper<BedUsage> updateWrapper2 = new UpdateWrapper<>();
            updateWrapper2.eq("bed_usage_id", bedCustomerUsage2.getBedUsageId())
                    .set("end_date", now);
            bedUsageMapper.update(null, updateWrapper2);

            // 创建新的床位使用记录
            BedUsage newBedUsage1 = new BedUsage();
            newBedUsage1.setBedId(bedCustomerUsage2.getBedId());
            newBedUsage1.setCustomerId(bedCustomerUsage1.getCustomerId());
            newBedUsage1.setStartDate(now);
            newBedUsage1.setEndDate(bedCustomerUsage1.getEndDate());
            bedUsageMapper.insert(newBedUsage1);

            BedUsage newBedUsage2 = new BedUsage();
            newBedUsage2.setBedId(bedCustomerUsage1.getBedId());
            newBedUsage2.setCustomerId(bedCustomerUsage2.getCustomerId());
            newBedUsage2.setStartDate(now);
            newBedUsage2.setEndDate(bedCustomerUsage2.getEndDate());
            bedUsageMapper.insert(newBedUsage2);

            // 对调客户对应的床位 ID
            customerClient.changeBed(bedCustomerUsage1.getCustomerId(), bedCustomerUsage2.getBedId());
            customerClient.changeBed(bedCustomerUsage2.getCustomerId(), bedCustomerUsage1.getBedId());
        }
    }
}
